package com.kingmed.kmss.admin.modules.sys.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingmed.kmss.admin.modules.sys.mapper.SysOpenGroupMapper;
import com.kingmed.kmss.admin.modules.sys.model.SysOpenGroup;
import com.kingmed.kmss.admin.modules.sys.service.ISysOpenGroupService;
import com.kingmed.kmss.admin.modules.sys.service.ISysOpenRelationService;
import com.kingmed.kmss.common.constant.common.CommonConstants;
import com.kingmed.kmss.common.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 对外授权组Service业务层处理
 *
 * @author Sys
 * @date 2022-12-16
 */
@Service
public class SysOpenGroupServiceImpl extends ServiceImpl<SysOpenGroupMapper, SysOpenGroup> implements ISysOpenGroupService
{
    @Autowired
    private SysOpenGroupMapper sysOpenGroupMapper;
    @Autowired
    @Lazy
    private ISysOpenRelationService openRelationService;

    /**
     * 查询对外授权组
     *
     * @param groupId 对外授权组主键
     * @return 对外授权组
     */
    @Override
    public SysOpenGroup selectSysOpenGroupByGroupId(String groupId)
    {
        return getById(groupId);
    }

    /**
     * 查询对外授权组列表
     *
     * @param sysOpenGroup 对外授权组
     * @return 对外授权组
     */
    @Override
    public List<SysOpenGroup> selectSysOpenGroupList(SysOpenGroup sysOpenGroup)
    {
        return sysOpenGroupMapper.selectSysOpenGroupList(sysOpenGroup);
    }

    /**
     * 分页
     * @param sysOpenGroup
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<SysOpenGroup> list(SysOpenGroup sysOpenGroup, Integer pageNum, Integer pageSize) {
        Page<SysOpenGroup> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysOpenGroup> wrapper = this.initBaseQueryWrapper(sysOpenGroup);
        return page(page, wrapper);
    }

    /**
     * 新增对外授权组
     *
     * @param sysOpenGroup 对外授权组
     * @return 结果
     */
    @Override
    public boolean insertSysOpenGroup(SysOpenGroup sysOpenGroup)
    {
        checkIsExist(sysOpenGroup, true);
        // 初始化token
        sysOpenGroup.setAppKey(RandomUtil.randomString(32));
        return save(sysOpenGroup);
    }

    /**
     * 修改对外授权组
     *
     * @param sysOpenGroup 对外授权组
     * @return 结果
     */
    @Override
    public boolean updateSysOpenGroup(SysOpenGroup sysOpenGroup)
    {
        checkIsExist(sysOpenGroup, false);
        // 不能更改token
        sysOpenGroup.setAppKey(null);
        return updateById(sysOpenGroup);
    }

    /**
     * 批量删除对外授权组
     *
     * @param groupIds 需要删除的对外授权组主键
     * @return 结果
     */
    @Override
    public boolean deleteSysOpenGroupByGroupIds(String[] groupIds)
    {
        if (groupIds == null || groupIds.length == 0){
            return false;
        }
        List<String> ids = Arrays.asList(groupIds);
        if (removeByIds(ids)){
            openRelationService.deleteByGroupId(ids);
            return true;
        }
        return false;
    }

    /**
     * 删除对外授权组信息
     *
     * @param groupId 对外授权组主键
     * @return 结果
     */
    @Override
    public boolean deleteSysOpenGroupByGroupId(String groupId)
    {
        if (StringUtils.isBlank(groupId)){
            return false;
        }
        if (removeById(groupId)){
            openRelationService.deleteByGroupId(groupId);
            return true;
        }
        return false;
    }

    /**
   * 根据主键集合获取数据
   * @return
   */
    @Override
    public Map<Long, SysOpenGroup> listByIdsReturnMap(List<Long> ids) {
        List<SysOpenGroup> list = listByIds(ids);
        if (CollectionUtils.isEmpty(list)){
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.toMap(p -> p.getGroupId(), p -> p ));
    }

    /**
    * 检查是否存在
    * @return
    */
    private boolean checkIsExist(SysOpenGroup sysOpenGroup, boolean isAdd){
        LambdaQueryWrapper<SysOpenGroup> wrapper = null;
        // 修改需要把主键设置为null
        SysOpenGroup updateQuery = new SysOpenGroup();
        updateQuery.setAppId(sysOpenGroup.getAppId());
        updateQuery.setName(sysOpenGroup.getName());
        if (!isAdd) {
            wrapper = initBaseQueryWrapper(updateQuery);
        }else {
            wrapper = initBaseQueryWrapper(sysOpenGroup);
        }
        wrapper.last(CommonConstants.LIMIT_ONE);
        SysOpenGroup sysOpenGroupEntity = getOne(wrapper);
        if (null != sysOpenGroupEntity){
            if (null !=sysOpenGroup.getGroupId() || !sysOpenGroupEntity.getGroupId().equals(sysOpenGroup.getGroupId())){
                throw new BusinessException("该信息已存在，请勿重复添加");
            }
        }
        return false;
    }

    /**
    * 初始化实体查询
    * @return
    */
    private LambdaQueryWrapper<SysOpenGroup> initBaseQueryWrapper(SysOpenGroup sysOpenGroup){
        LambdaQueryWrapper<SysOpenGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null !=sysOpenGroup.getGroupId(), SysOpenGroup::getGroupId, sysOpenGroup.getGroupId());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getAppId()), SysOpenGroup::getAppId, sysOpenGroup.getAppId());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getName()), SysOpenGroup::getName, sysOpenGroup.getName());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getAppKey()), SysOpenGroup::getAppKey, sysOpenGroup.getAppKey());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getStatus()), SysOpenGroup::getStatus, sysOpenGroup.getStatus());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getCreateBy()), SysOpenGroup::getCreateBy, sysOpenGroup.getCreateBy());
        wrapper.eq(null != sysOpenGroup.getCreateTime(), SysOpenGroup::getCreateTime, sysOpenGroup.getCreateTime());
        wrapper.eq(StringUtils.isNotBlank(sysOpenGroup.getUpdateBy()), SysOpenGroup::getUpdateBy, sysOpenGroup.getUpdateBy());
        wrapper.eq(null != sysOpenGroup.getUpdateTime(), SysOpenGroup::getUpdateTime, sysOpenGroup.getUpdateTime());
        return wrapper;
    }

}
